import React, { useEffect, useRef, useState } from 'react'
import ArticleItem from '../ArticleItem'
import { fetchArticleList } from '@/apis/article'
import type { ArticeInfo } from '@/apis/article'
type Prop = {
  channelId: string
  style?: React.CSSProperties
}
import './index.scss'
import { InfiniteScroll, PullToRefresh, Toast } from 'antd-mobile'

const ArticleList: React.FC<Prop> = (props) => {
  const { channelId } = props
  // 上一次的时间戳
  const timestamp = useRef('')
  // 组件状态
  // 是否在加载中
  const [isLoad, setIsLoad] = useState(false)
  // 是否还有更多数据
  const [hasMore, setHasMore] = useState(false) //一开始必须设置为false,否则一开始会触发onLoadMore
  // 文章列表
  const [articleList, setArticleList] = useState<ArticeInfo[]>([])
  useEffect(() => {
    // 根据频道id获取文章列表
    // eslint-disable-next-line no-extra-semi
    ;(async () => {
      setIsLoad(true)
      const res = await fetchArticleList(channelId, Date.now().toString())
      setArticleList(res.data.results)
      timestamp.current = res.data.pre_timestamp
      setHasMore(res.data.results.length !== 0)
      setIsLoad(false)
    })()
  }, [channelId])

  // 事件处理函数
  /**
   * 上拉加载更多
   */
  async function onLoadMore() {
    if (isLoad) return
    setIsLoad(true)
    const res = await fetchArticleList(channelId, timestamp.current)
    setArticleList([...articleList, ...res.data.results])
    setHasMore(res.data.results.length !== 0)
    timestamp.current = res.data.pre_timestamp
    setIsLoad(false)
  }
  /**
   * 下拉刷新
   */
  async function onPullToRefresh() {
    if (isLoad) return Toast.show('正在加载中...')
    setIsLoad(true)
    timestamp.current = Date.now().toString() // 更新时间戳
    const res = await fetchArticleList(channelId, timestamp.current)
    setArticleList(res.data.results)
    setIsLoad(false)
  }

  return (
    <div className="article-list-container" style={props.style}>
      <PullToRefresh onRefresh={onPullToRefresh}>
        {articleList.map((item) => (
          <ArticleItem articleInfo={item} key={item.art_id}></ArticleItem>
        ))}
        {/* 无限滚动-上拉加载更多 */}
        <InfiniteScroll
          loadMore={onLoadMore}
          hasMore={hasMore}
        ></InfiniteScroll>
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
